﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using Yuecai.Storage;

namespace Yuecai.DynamicKey
{
    /// <summary>
    /// 动态口令中矩阵代码相关操作
    /// </summary>
    public class DynamicKey
    {
        //TODO 是否可以考虑通过USB直接跟手机客户端联系

        /// <summary>
        /// 生成矩阵代码并保存，仅仅第一次使用软件的时候运行一次
        /// </summary>
        /// <param name="path">矩阵代码外部文件的保存位置</param>
        /// <param name="key">密码</param>
        /// <returns>是否成功</returns>
        public static bool GenerateMatrix(string path, string key)
        {
            var buf = new byte[0xff*0xff*0xff];
            var rd = new Random();
            for (var i = 0; i < 0xff*0xff*0xff; i++)
            {
                switch (rd.Next(3))
                {
                    case 0:
                        buf[i] = (byte) rd.Next(48, 57);
                        break;
                    case 1:
                        buf[i] = (byte) rd.Next(65, 90);
                        break;
                    default:
                        buf[i] = (byte) rd.Next(97, 122);
                        break;
                }
            }

            FileStorage.Write(Encoding.Default.GetString(buf), path, key);
            XmlStorage.SetData("matrix", Encoding.Default.GetString(buf));
            return true;
        }

        /// <summary>
        /// 生成下一个矩阵原码
        /// </summary>
        /// <returns></returns>
        public static string NextCode()
        {
            var rd = new Random();
            return rd.Next(0xff).ToString("X") + rd.Next(0xff).ToString("X") + rd.Next(0xff).ToString("X");
        }

        /// <summary>
        /// 获取动态口令
        /// </summary>
        /// <param name="code">矩阵原码</param>
        /// <returns>口令</returns>
        public static string GetDynamicKey(string code)
        {
            int x = int.Parse(code.Substring(0, 2), NumberStyles.HexNumber);
            int y = int.Parse(code.Substring(2, 2), NumberStyles.HexNumber);
            int z = int.Parse(code.Substring(4, 2), NumberStyles.HexNumber);
            var buf = Encoding.Default.GetBytes(XmlStorage.GetData("matrix"));
            return buf[x*0xff*0xff + y*0xff + z] +
                   buf[x*0xff*0xff + z*0xff + y] +
                   buf[y*0xff*0xff + x*0xff + z] +
                   buf[y*0xff*0xff + z*0xff + x] +
                   buf[z*0xff*0xff + x*0xff + y] +
                   buf[z*0xff*0xff + y*0xff + x].ToString();
        }
    }
}
